import os

import codecs
import json 
import re

root_path = r"D:\code\publish-common\pm-unit\demo-gradio\flagged\chat-cache\2024-07-15\经济模型200个"

outfiles = list()
for f in os.listdir(root_path):
    with codecs.open(os.path.join(root_path, f), "r", "utf-8") as fp:
        flag = False
        begin  =False
        lines = list()
        for line in fp.readlines():
            if line.startswith("{'v0': '"):
                target_name = json.loads(line.replace('\'', '\"')).get('v0')
            if line.startswith("```python"):
                flag = True
                continue
            elif line.startswith("```"):
                flag = False
                break
            if line.startswith("请求结果："):
                begin = True
                continue
            
            if begin:
                if flag:
                    lines.append(line)
                else:
                    
                    lines.append(f'# {line}')
        # format target_name to file name
        target_name = re.sub(r'[^a-zA-Z0-9\u4e00-\u9fa5\.]', '', target_name)
        target = os.path.join('经济学模型', f'{target_name}.py')
        with codecs.open(target, "w", "utf-8") as fp:
            fp.write("\n".join(lines))
        
        outfiles.append(target)
outfiles = os.listdir('经济学模型', )

for f in outfiles:
    # 假设 funcstr 是包含函数定义的字符串  
    funcstr = codecs.open(os.path.join('经济学模型', f), "r", "utf-8").read()
    
    # 创建一个受限的命名空间（字典）  
    restricted_globals = {  
        "__builtins__": {},  # 禁用所有内置函数和变量  
        "print": print,     # 可选：如果你需要允许打印功能，可以提供一个受限的版本  
        "__import__": __import__,
        "open": open,
        "os": os,
        "codecs": codecs,
        "json": json,
        "re": re,
    }  
    
    restricted_locals = {}  
    
    # 编译字符串为代码对象  
    code_obj = compile(funcstr, '<string>', 'exec')  
    
    # 在受限的命名空间中执行代码  
    exec(code_obj, restricted_globals, restricted_locals)  
    
    break